package util;

import play.Logger;
import ch.bfh.abcm.rems.sensors.tinkerforge.TFSensorType;

public class UnitConverter_CM {

    public static int convertTFValuetoNormValue(TFSensorType sensorType, int TFValue) {
        int factor = (int) Math.pow(10, sensorType.getDecimalDigits());
        int normValue = TFValue / factor;
        Logger.debug("convertTFValuetoNormValue: Type: %s DecimalDigits: %s factor: %s NormValue: %s TFValue: %s",
                sensorType, sensorType.getDecimalDigits(), factor, normValue, TFValue);
        return normValue;
    }

    public static int convertNormValuetoTFValue(TFSensorType sensorType, int normValue) {
        int factor = (int) Math.pow(10, sensorType.getDecimalDigits());
        int TFValue = normValue * factor;
        Logger.debug("convertNormValuetoTFValue: Type: %s DecimalDigits: %s factor: %s NormValue: %s TFValue: %s",
                sensorType, sensorType.getDecimalDigits(), factor, normValue, TFValue);
        return TFValue;
    }

    public static String convertNormValuetoTFValue(TFSensorType sensorType, String normValue) {
        int value = convertNormValuetoTFValue(sensorType, Integer.valueOf(normValue));
        return ""+value;
    }

    public static String convertTFValuetoNormValue(TFSensorType sensorType, String TFValue) {
        int value = convertTFValuetoNormValue(sensorType, Integer.valueOf(TFValue));
        return ""+value;
    }
    
    public static String convertNormValuetoTFValue(String propertyKey, String normValue) {
        int value = convertNormValuetoTFValue(findSensorTypebyKey(propertyKey), Integer.valueOf(normValue));
        return ""+value;
    }
    
    public static String convertTFValuetoNormValue(String propertyKey, String TFValue) {
        int value = convertTFValuetoNormValue(findSensorTypebyKey(propertyKey), Integer.valueOf(TFValue));
        return ""+value;
    }

    private static TFSensorType findSensorTypebyKey(String propertyKey){
        String name = "";
        TFSensorType sensorType = null;
        try {
            name = propertyKey.split("_")[0];
            sensorType = TFSensorType.valueOf(name);
        } catch (Exception e) {
            return TFSensorType.AMBIENT;
        }
        if (sensorType == null) {
            return TFSensorType.AMBIENT;
        }
        return sensorType;
    }
}
